<?php

namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class OrderValidityEnd extends Command
{

    // 会员卡类型
    protected static $type = [
        1 => '次卡',
        2 => '私教卡',
        3 => '周卡',
        4 => '月卡',
        5 => '学生卡'
    ];

    protected function configure()
    {
        $this->setName('order_validity')->setDescription('【有效时间】到期，订单过期、自动分润');
    }

    protected function execute(Input $input, Output $output)
    {
        ini_set('default_socket_timeout', -1);  //不超时
        $redis = new \Redis();
        $redis->pconnect(config('redis.host'), config('redis.port'), config('redis.timeout'));
        $redis->select(3);

        // 订单【有效时间】到期
        $redis->psubscribe(['__keyevent@3__:expired'], function ($redis, $pattern, $channel, $message) use ($output) {
            Db::startTrans();
            try {
                // 订单过期
                $order = Db::name('order')->where(['numbers' => $message])->find();
                if ($order) {
                    Db::name('order')->where(['numbers' => $message])->update(['status' => 3, 'updatetime' => time()]);
                    $gymnasium = Db::name('gymnasium')->where(['id' => $order['gymnasium_id']])->field('percentage')->find();

                    // 自动分润
                    $money = $order['total_price'] * (1 - $gymnasium['percentage']);
                    $user  = Db::name('user')->field('mobile,name')->find($order['user_id']);

                    Db::name('gymnasium_finance')->where(['gymnasium_id' => $order['gymnasium_id']])->setInc('balance', $money);
                    Db::name('gymnasium_finance_income')->insert([
                        'gymnasium_id' => $order['gymnasium_id'],
                        'order_id'     => $message,
                        'money'        => $money,
                        'remarks'      => $user['name'] . '【' . $user['mobile'] . '】 有效时间到期 ' . '【' . self::$type[$order['good_type']] . '】' . $order['good_name'],
                        'createtime'   => time(),
                    ]);
                }

                Db::commit();
                Log::info('ORDER_VALIDITY_END 订单号：' . $message);
            } catch (\Exception $e) {
                Db::rollback();
                // 记录错误日志
                Log::error('订单【有效时间】到期');
                Log::info('ORDER_VALIDITY_END 订单号：' . $message);
                Log::error($e->getMessage());
            }
        });
    }
}

